/**
 * ajax 成功
 * @param result
 * @param handleSucResult
 */
function ajaxSuccess(result, handleSucResult, hideSucAlert) {
    if (result === null || result === undefined) {
        alert('请求失败');
        return;
    }
    if (result.code !== 200) {
        alert(result.msg);
    } else {
        if (!hideSucAlert) {
            alert(result.msg);
        }
        if (handleSucResult) {
            handleSucResult();
        }
    }
}

/**
 * ajax 失败
 * @param xhr
 */
function ajaxError(xhr) {
    if (xhr.status === 401) {
        alert('您的登录已过期，请重新登录');
        window.location.href = '/blog/login';
    } else {
        alert('请求出错');
    }
}

// 评论、标签切换，加载更多
$(function () {

    $('.blog_card_comment_click').click(function () {
        var my = $(this);
        let key = my.attr('key');
        $('#' + key).slideToggle();
        // 判断是否需要加载评论列表
        if (!my.attr('data-load')) {
            $.ajax({
                url: '/blog/api/commentList',
                method: 'GET',
                data: {
                    id: my.attr('data-blog'),
                },
                success: function (result) {
                    ajaxSuccess(result, function () {
                        my.attr('data-load', true);
                        var data = result.data;
                        if (data && data.length > 0) {
                            var wrapper = $('#' + my.attr('data-list'));
                            for (var i = 0; i < data.length; i++) {
                                var comment = data[i];
                                var cDiv = $('<div></div>');
                                var html = '<div style="margin-top: 16px;">' +
                                    '<img class="blog_card_header_img" src="img/user.jpg" alt="user">' +
                                    '<div class="blog_card_header_info">' +
                                    '    <div class="blog_card_header_name">' + comment.user.nick
                                    + '</div>' +
                                    '    <div class="blog_card_header_time">' + comment.createTime
                                    + '</div>' +
                                    '</div>' +
                                    '<div class="blog_card_content">' + comment.content +
                                    '</div>' +
                                    '</div>'
                                cDiv.html(html);
                                wrapper.append(cDiv);
                            }
                        }
                    }, true);
                },
                error: ajaxError
            })
        }
    });

    var blogListLable = $('.blog_list_label');

    var currentBlogList = $('#blog_list_1');

    blogListLable.click(function () {
        blogListLable.removeClass('blog_list_label_active');
        let tmp = $(this);
        tmp.addClass('blog_list_label_active');

        currentBlogList.fadeOut(200, function () {
            let key = tmp.attr('key');
            currentBlogList = $('#' + key);
            currentBlogList.fadeIn(100);
        })
    });

    $('.load_more').click(function () {
        var my = $(this);
        var type = my.attr('data-type');
        $.ajax({
            url: '/blog/api/blogs',
            method: 'GET',
            data: {
                id: my.attr('data-id'),
                type: type,
                count: 10
            },
            success: function (result) {
                ajaxSuccess(result, function () {
                    var data = result.data;
                    if (!data || data.length < 1) {
                        // 没数据了
                        alert('没有更多数据了')
                        my.hide();
                    } else {
                        my.attr('data-id', data[data.length - 1].id);
                        var wrapper = $('#' + my.attr('data-list'));
                        for (var i = 0; i < data.length; i++) {
                            var blog = data[i];
                            var cDiv = $('<div></div>');
                            cDiv.html(
                                '<div class="blog_card blog_item_card">' +
                                '    <div class="blog_card_header">' +
                                '        <img class="blog_card_header_img" src="img/user.jpg" alt="user">' +
                                '        <div class="blog_card_header_info">' +
                                '            <div class="blog_card_header_name">' + blog.user.nick +
                                '            </div>' +
                                '            <div class="blog_card_header_time">' + blog.createTime +
                                '            </div>' +
                                '        </div>' +
                                '    </div>' +
                                '    <div class="blog_card_content">' + blog.content +
                                '    </div>' +
                                '    <div class="blog_card_action">' +
                                '        <a href="javascript:void(0);"' +
                                '           class="blog_thumbs blog_card_action_item ' + (blog.thumbs ? 'blog_card_action_item_active' : '') + '"' +
                                '           data="' + blog.id + '">' +
                                '            <span class="blog_card_action_item_star"></span>' + blog.thumbsUp +
                                '        </a>' +
                                '        <a href=" javascript:void(0)" class="blog_card_action_item blog_card_comment_click"' +
                                '           key="comment_' + type + '_' + blog.id + '">' +
                                '            <span class="blog_card_action_item_comment"></span>' + blog.comment +
                                '        </a>' +
                                '    </div>' +
                                '    <div class="blog_card_comment" style="display: none;" id="comment_' + type + '_' + blog.id + '">' +
                                '        <div class="blog_card_comment_action">' +
                                '            <input id="cinput_' + type + '_' + blog.id + '" class="blog_card_comment_input" type="text"' +
                                '                   placeholder="输入您的评论..."/>' +
                                '            <button data-input="cinput_' + type + '_' + blog.id + '"' +
                                '                    data-blog="' + blog.id + '"' +
                                '                    data-list="comment_' + type + '_' + blog.id + '_wrapper"' +
                                '                    class="blog_card_comment_button publish_comment" type="button">评论' +
                                '            </button>' +
                                '        </div>' +
                                '        <div id="comment_' + type + '_' + blog.id + '_wrapper"></div>' +
                                '    </div>' +
                                '</div>'
                            );
                            wrapper.append(cDiv);
                        }
                    }
                }, true);
            },
            error: ajaxError,
        })
    });
});

// 用户资料对话框控制
$(function () {
    var editModal = $('#edit_modal');
    var userName = $('.user_name');
    var userSign = $('.user_sign');
    var userNameInput = $('#user_name_input');
    var userSignInput = $('#user_sign_input');

    $('#button_edit').click(function () {
        editModal.fadeIn(200);
        userNameInput.val(userName.text());
        userSignInput.val(userSign.text());
    });
    $('#edit_cancel').click(function () {
        editModal.fadeOut(200);
    });
    $('#edit_submit').click(function () {
        var nick = userNameInput.val();
        var sign = userSignInput.val();
        if (nick === null || nick === undefined
            || nick.length < 1) {
            alert('昵称不能为空');
            return;
        }
        if (nick.length > 20) {
            alert('昵称太长啦');
            return;
        }
        if (sign && sign.length > 500) {
            alert('个性签名太长啦');
            return;
        }

        $.ajax({
            url: '/blog/api/updateUser',
            method: 'POST',
            data: {
                nick: nick,
                sign: sign,
            },
            success: function (result) {
                if (result === null || result === undefined) {
                    alert('请求失败');
                    return;
                }
                if (result.code !== 200) {
                    alert(result.msg);
                } else {
                    alert(result.msg);
                    userName.text(nick);
                    userSign.text(sign);
                    editModal.fadeOut(200);
                }
            },
            error: function (xhr) {
                if (xhr.status === 401) {
                    alert('您的登录已过期，请重新登录');
                    window.location.href = '/blog/login';
                } else {
                    alert('请求出错');
                }
            }
        });


    });
});

// 发布微博对话框控制
$(function () {
    var publishModal = $('#publish_modal');
    var publishInput = $('#blog_input');

    $('#button_publish').click(function () {
        publishModal.fadeIn(200);
    });
    $('#publish_cancel').click(function () {
        publishInput.val('');
        publishModal.fadeOut(200);
    });
    $('#publish_submit').click(function () {
        var content = publishInput.val();
        if (content === null || content === undefined
            || content.length < 1 || content.length > 500) {
            alert('微博内容不正确');
            return;
        }

        $.ajax({
            url: '/blog/api/publishBlog',
            method: 'POST',
            data: {
                content: content,
            },
            success: function (result) {
                ajaxSuccess(result, function () {
                    publishInput.val('');
                    publishModal.fadeOut(200);
                })
            },
            error: ajaxError
        });
    });
});

// 退出登录
$(function () {
    $('#logout').click(function () {
        window.location.href = '/blog/logout';
    });
});

//微博点赞
$(function () {
    $('.blog_thumbs').click(function () {
        var my = $(this);
        $.ajax({
            url: '/blog/api/thumbs',
            method: 'POST',
            data: {
                id: my.attr('data')
            },
            success: function (result) {
                ajaxSuccess(result, function () {
                    my.addClass('blog_card_action_item_active');
                    my.html(
                        '<span class="blog_card_action_item_star"></span> ' +
                        (parseInt(my.text()) + 1)
                    );
                })
            },
            error: ajaxError
        })
    });
});

// 发布评论
$(function () {
    $('.publish_comment').click(function () {
        var my = $(this);
        var blogId = my.attr('data-blog');
        var input = $('#' + my.attr('data-input'));
        var content = input.val();
        if (content === null || content.length < 1) {
            alert('请输入评论内容');
            return;
        }
        $.ajax({
            url: '/blog/api/publishComment',
            method: 'POST',
            data: {
                id: blogId,
                content: content,
            },
            success: function (result) {
                ajaxSuccess(result, function () {
                    input.val('');
                    var div = $('#' + my.attr('data-list'));
                    var cDiv = $('<div></div>');
                    var html = '<div style="margin-top: 16px;">' +
                        '<img class="blog_card_header_img" src="img/user.jpg" alt="user">' +
                        '<div class="blog_card_header_info">' +
                        '    <div class="blog_card_header_name">' +
                        $('.user_name').text()
                        + '</div>' +
                        '    <div class="blog_card_header_time">' +
                        new Date().toLocaleString()
                        + '</div>' +
                        '</div>' +
                        '<div class="blog_card_content">' +
                        content +
                        '</div>' +
                        '</div>'
                    cDiv.html(html);
                    div.prepend(cDiv);
                    var dataNumber = $('#' + my.attr('data-number'));
                    dataNumber.html(
                        '<span class="blog_card_action_item_comment"></span> ' +
                        (parseInt(dataNumber.text()) + 1)
                    );
                })
            },
            error: ajaxError
        })
    });
});